package ldh.im.fxbase.data.event;

import com.google.common.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class EventBusFactory {


    private static final Logger LOGGER = LoggerFactory.getLogger(EventBusFactory.class);

    private static EventBusFactory instance = null;
    private EventBus eventBus = new EventBus();
    private Map<Object, String> registerObjectMap = new ConcurrentHashMap<>();

    private EventBusFactory() {}

    public static EventBusFactory getInstance() {
        if (instance == null) {
            synchronized (EventBusFactory.class) {
                if (instance == null) {
                    instance = new EventBusFactory();
                }
            }
        }
        return instance;
    }

    public void register(Object obj) {
        LOGGER.info("event bus register {}, size {}", obj, registerObjectMap.size());
        eventBus.register(obj);
        registerObjectMap.put(obj, obj.toString());
    }

    public void unregister(Object obj) {
        if (obj == null) return;
        eventBus.unregister(obj);
        registerObjectMap.remove(obj);
    }

    public void post(Object obj) {
        eventBus.post(obj);
    }

}
